package start

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"time"
)

func NewHttpServer(l *zap.Logger) *HttpServer {
	r := gin.Default()
	server := &http.Server{
		ReadHeaderTimeout: 60 * time.Second,
		WriteTimeout:      60 * time.Second,
		ReadTimeout:       69 * time.Second,
		IdleTimeout:       60 * time.Second,
		MaxHeaderBytes:    1 << 20, //1m
		Addr:              ":9080",
		Handler:           r,
	}
	return &HttpServer{
		Server: server,
		l:      l,
		R:      r,
	}
}

type HttpServer struct {
	Server *http.Server
	l      *zap.Logger
	R      gin.IRouter
}

func (h *HttpServer) Start() error {
	if err := h.Server.ListenAndServe(); err != nil {
		h.l.Error("启动http服务失败", zap.Error(err))
		return err
	}
	return nil
}

func (h *HttpServer) Stop() error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
	defer cancel()
	if err := h.Server.Shutdown(ctx); err != nil {
		h.l.Warn("关闭http服务失败", zap.Error(err))
		return err
	}
	h.l.Info("关闭http服务成功...")
	return nil
}
